var operationReport = function() {
	return {
		/**
		 * 页面初始化方法
		 */
		init: function() {

			$("#shortcut_time").val("2");

			//设置报告生成参数
			operationReport._setReportParam();
			//设置报告生成日期
			operationReport._setReportCreateDate();
			//
			operationReport._setAlertBarGraph();
			operationReport._setAlertPieChart();
			operationReport._setSaleSupportPieChart();
			//下载报告
			operationReport._downloadReport();
			//设置报告生成人
			operationReport._getUserNameByLoginName();
			operationReport._setBatteryBasicInfo();
			//
			//operationReport._setRealTime();
			operationReport._initShortcutOfDate();
			//查询报告
			$("#btn_query").on('click',  function(e) {
				e.preventDefault();
				operationReport._setReportCreateDate();
				operationReport._setAlertBarGraph();
				operationReport._setAlertPieChart();
				operationReport._setSaleSupportPieChart();
				operationReport._setBatteryBasicInfo();
			});
		},

		_initShortcutOfDate : function() {
			/*$.ajax({
				"type": "post",
				"url": "main/realtimeBoard/getShortcutOfDate.mvc",
				"async": true,
				"dataType": "json",
				"success": function(res) {
					$("#gatherTime_start").val(res.beginDayOfLastMonth);
					$("#gatherTime_end").val(res.endDayOfLastMonth);
				}
			});*/

			$("#shortcut_time").on('change', function(e) {
				var _dateType = $("#shortcut_time").val();
				$.ajax({
					"type": "post",
					"url": "main/realtimeBoard/getShortcutOfDate.mvc",
					"async": true,
					"dataType": "json",
					"success": function(res) {
						if (_dateType == '0') {
							$("#gatherTime_start").val(res.yesterdayStart);
							$("#gatherTime_end").val(res.yesterdayEnd);
						} else if (_dateType == '1') {
							$("#gatherTime_start").val(res.beginDayOfLastWeek);
							$("#gatherTime_end").val(res.endDayOfLastWeek);
						} else if (_dateType == '2') {
							$("#gatherTime_start").val(res.beginDayOfLastMonth);
							$("#gatherTime_end").val(res.endDayOfLastMonth);
						} else if (_dateType == '3') {
							$("#gatherTime_start").val(res.beginOfLastQuarter);
							$("#gatherTime_end").val(res.endOfLastQuarter);
						} else if (_dateType == '4') {
							$("#gatherTime_start").val(res.beginOfLastYear);
							$("#gatherTime_end").val(res.endOfLastYear);
						}  else if (_dateType == '5') {
							$("#gatherTime_start").val('');
							$("#gatherTime_end").val('');
						}
					}
				});
			});
			
		},

		/**
		 * 配置echart
		 * @param title 图表标题
		 * @param legendData 系列
		 * @param dataX x轴数据
		 * @param unit y轴单位
		 * @param 系列数据
		 * @param chart_div_id 图表div_id
		 */
		_alertBarGraphConfig: function(title, legendData, dataX, unit, series, chart_div_id, yaxisName, tooltipFormat) {
			
			option = {
				title: {
					text: title
				},
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					data: ['告警分类']
				},
				toolbox: {
					show: true,
					feature: {
						mark: {
							show: true
						},
						dataView: {
							show: true,
							readOnly: false
						},
						magicType: {
							show: true,
							type: ['line', 'bar']
						},
						restore: {
							show: true
						},
						saveAsImage: {
							show: true
						}
					}
				},
				calculable: true,
				xAxis: [{
					type: 'category',
					data: dataX
				}],
				yAxis: [{
					type: 'value'
				}],
				series: series
			};
			
			var myChart = echarts.init(document.getElementById(chart_div_id));
			myChart.setOption(option, true);
			//App.unblockUI($("#battery_alert_chart_div")); //停止loading
		},

		/**
		 * [_setRealTime echarts3.0去除了addData接口,需手动实现动态数据加载功能]
		 */
		_setRealTime : function () {
			var option = {
				title: {
					text: '动态数据',
					subtext: '纯属虚构'
				},
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					data: ['预购队列']
				},
				toolbox: {
					show: true,
					feature: {
						/*mark: {
							show: true
						},*/
						dataView: {
							show: true,
							readOnly: false
						},
						magicType: {
							show: true,
							type: ['line', 'bar']
						},
						restore: {
							show: true
						},
						saveAsImage: {
							show: true
						}
					}
				},
				dataZoom: {
					show: false,
					start: 0,
					end: 100
				},
				xAxis: [ {
					type: 'category',
					boundaryGap: true,
					data: (function() {
						var now = new Date();
						var res = [];
						res.push(now.toLocaleTimeString().replace(/^\D*/, ''));
						return res;
					})()
				}],
				yAxis: [{
					type: 'value',
					scale: true,
					name: '预购量',
					boundaryGap: [0.2,0.2],
					min:0
				}],
				series: [{
					name: '最新成交价',
					type: 'line',
					markPoint: {
						data: [{
							type: 'max',
							name: '最大值'
						}, {
							type: 'min',
							name: '最小值'
						}]
					},
					data: (function() {
						var res = [];
						var len = 1;
						while (len--) {
							res.push((Math.random() * 10 + 5).toFixed(1) - 0);
						}
						return res;
					})()
				}]
			};
			var myChart = echarts.init(document.getElementById("battery_alert_chart_div"));
			var type = option.series[0].type;
			//绑定magictypechanged切换事件，切换echarts显示
			myChart.on('magictypechanged', function(param){
				type = param.newOption.series[0].type;
			});
			myChart.setOption(option, true);
			var lastData = 11;
			var axisData;
			var i = 0;
			//clearInterval(timeTicket);
			timeTicket = setInterval(function() {
				var flag = true;
				lastData += Math.random() * ((Math.round(Math.random() * 10) % 2) == 0 ? 1 : -1);
				lastData = lastData.toFixed(1) - 0;
				axisData = (new Date()).toLocaleTimeString().replace(/^\D*/, '');
				// 动态数据接口 addData
				i++;
				if(i>10){
					flag = false;
				}
				//
				var xAxis_data = option.xAxis[0].data ;
				xAxis_data.push(axisData);
				if(!flag){
					xAxis_data.shift();
				}
				option.xAxis[0].data = xAxis_data;
				var series_data = option.series[0].data ;
				series_data.push(lastData);
				if(!flag){
					series_data.shift();
				}
				option.series[0].data = series_data;

				//var series_type = option.series[0].type;
				//console.log(series_type);
				option.series[0].type = type;
				myChart.setOption(option);
			   /* myChart.addData([
			        [
			            0,        // 系列索引
			            Math.round(Math.random() * 1000), // 新增数据
			            true,     // 新增数据是否从队列头部插入
			            false     // 是否增加队列长度，false则自定删除原有数据，队头插入删队尾，队尾插入删队头
			        ],
			        [
			            0,        // 系列索引
			            lastData, // 新增数据
			            false,    // 新增数据是否从队列头部插入
			            flag,    // 是否增加队列长度，false则自定删除原有数据，队头插入删队尾，队尾插入删队头
			            axisData  // 坐标轴标签
			        ]
			    ]);*/
			}, 2100);
                    
		},



		/**
		 * 进入页面加载空表格
		 */
		_setAlertBarGraph : function() {
			var customerId = $("#id_customer").val();
			var gatherTimeStart = $("#gatherTime_start").val();
			var gatherTimeEnd = $("#gatherTime_end").val();
			$.ajax({
				"type": "post",
				"url": "main/report/getAlertData.mvc",
				"async": true,
				"data": {
					"customerId":customerId,
					"gatherTimeStart":gatherTimeStart,
					"gatherTimeEnd":gatherTimeEnd
				},
				"dataType": "json",
				"success": function(res) {
					var category = new Array();
					var count = new Array();
					for (var i = 0; i < res.length; i++) {
						category.push(res[i].alertName);
						count.push(res[i].num);
					}
					var series = [{
						name: '告警分类',
						type: 'bar',
						data: count,
						barWidth : 40,//柱图宽度
						/*markPoint: {
							data: [{
								type: 'max',
								name: '最大值'
							}, {
								type: 'min',
								name: '最小值'
							}]
						},*/
						itemStyle: {
							normal: {
								color: '#FF7F50',
								label: {
									show: true,
									position: 'top'
								}
							}
						}
					}];
					operationReport._alertBarGraphConfig("告警分类统计：", [''], category, '', series, "battery_alert_chart_div", '数量');
				}

			});
		},

		
		/**
		 * [_alertPieChartConfig description]
		 * @param  {[type]} legendData [description]
		 * @param  {[type]} seriesData [description]
		 * @return {[type]}            [description]
		 */
		_alertPieChartConfig : function(legendData,seriesData) {
			var option = {
				title: {
					text: '告警级别统计',
					x: 'center'
				},
				tooltip: {
					trigger: 'item',
					formatter: "{a} <br/>{b} : {c} ({d}%)"
				},
				legend: {
					orient: 'vertical',
					x: 'left',
					data: legendData
				},
				toolbox: {
					show: true,
					feature: {
						mark: {
							show: true
						},
						dataView: {
							show: true,
							readOnly: false
						},
						magicType: {
							show: true,
							type: ['pie', 'funnel'],
							option: {
								funnel: {
									x: '25%',
									width: '50%',
									funnelAlign: 'left',
									max: 1548
								}
							}
						},
						restore: {
							show: true
						},
						saveAsImage: {
							show: true
						}
					}
				},
				calculable: true,
				series: [{
					name: '告警级别',
					type: 'pie',
					radius: '55%',
					center: ['50%', '60%'],
					label: {
						normal: {
							show: true,
							formatter: '{b}: {c}({d}%)'
						}
					},
					data: seriesData
				}]
			};
			var myChart = echarts.init(document.getElementById("battery_alert_chart_div2"));
			myChart.setOption(option, true);
                    
		},



		_setAlertPieChart :function() {
			var customerId = $("#id_customer").val();
			var gatherTimeStart = $("#gatherTime_start").val();
			var gatherTimeEnd = $("#gatherTime_end").val();
			$.ajax({
				"type": "post",
				"url": "main/report/getAlertPieChartData.mvc",
				"async": true,
				"data": {
					"customerId":customerId,
					"gatherTimeStart":gatherTimeStart,
					"gatherTimeEnd":gatherTimeEnd
				},
				"dataType": "json",
				/*"beforeSend": function() {
					console.log("执行前");
					App.blockUI($(".battery_alert_chart_div"));
				},*/
				"success": function(res) {
					var legendData = res.legendData;
					var seriesData = res.seriesData;
					operationReport._alertPieChartConfig(legendData,seriesData);
				}/*,
				"complete": function() {
					App.unblockUI($(".battery_alert_chart_div"));
				}*/

			});			
		},

		_saleSupportPieChartConfig : function(title,subtext,legendData,seriesData,seriesName,divId) {
			var option = {
				title: {
					text: title,
					subtext: subtext,
					x: 'center'
				},
				tooltip: {
					trigger: 'item',
					formatter: "{a} <br/>{b} : {c} ({d}%)"
				},
				legend: {
					orient: 'vertical',
					x: 'left',
					data: legendData
				},
				toolbox: {
					show: true,
					feature: {
						mark: {
							show: true
						},
						dataView: {
							show: true,
							readOnly: false
						},
						magicType: {
							show: true,
							type: ['pie', 'funnel'],
							option: {
								funnel: {
									x: '25%',
									width: '50%',
									funnelAlign: 'left',
									max: 1548
								}
							}
						},
						restore: {
							show: true
						},
						saveAsImage: {
							show: true
						}
					}
				},
				calculable: true,
				series: [{
					name: seriesName,
					type: 'pie',
					radius: '55%',
					center: ['50%', '60%'],
					label: {
						normal: {
							show: true,
							formatter: '{b}: {c}({d}%)'
						}
					},
					data: seriesData
				}]
			};
			var myChart = echarts.init(document.getElementById(divId));
			myChart.setOption(option, true);
		},

		_setSaleSupportPieChart : function() {
			var customerId = $("#id_customer").val();
			var gatherTimeStart = $("#gatherTime_start").val();
			var gatherTimeEnd = $("#gatherTime_end").val();
			$.ajax({
				"type": "post",
				"url": "main/report/getSaleSupportChartData.mvc",
				"async": true,
				"data": {
					"customerId":customerId,
					"gatherTimeStart":gatherTimeStart,
					"gatherTimeEnd":gatherTimeEnd
				},
				"dataType": "json",
				"success": function(res) {
					var reqLegendData = res.reqLegendData;
					var reqSeriesData = res.reqSeriesData;
					var woLegendData = res.woLegendData;
					var woSeriesData = res.woSeriesData;
					operationReport._saleSupportPieChartConfig("服务请求分析统计",'请求总数:'+res.reqTotalNumber,reqLegendData,reqSeriesData,"服务请求","service_chart_div");
					operationReport._saleSupportPieChartConfig("服务工单分析统计",'工单总数:'+res.woTotalNumber,woLegendData,woSeriesData,"服务工单","service_chart_div2");
				}

			});	
		},

		/**
		 * [_downloadReport 下载报告]
		 * @return {[type]} [description]
		 */
		_downloadReport: function() {
			//var downPdf = document.getElementById("renderPdf");
			$("#btn_download").on("click", function(){
				html2canvas($("#operationReport"), {
					onrendered: function(canvas) {

						//返回图片dataURL，参数：图片格式和清晰度(0-1)
						var pageData = canvas.toDataURL('image/png', 1.0);

						//方向默认竖直，尺寸ponits，格式a4[595.28,841.89]
						var pdf = new jsPDF('', 'pt', 'a4');

						//addImage后两个参数控制添加图片的尺寸，此处将页面高度按照a4纸宽高比列进行压缩
						pdf.addImage(pageData, 'png', 25, 25, 595.28-48, (595.28) / canvas.width * canvas.height);

						pdf.save('青岛力神报告.pdf');

					}
				});
			});
			
		},

		/**
		 * [_setReportParam 设置报告初始化参数]
		 */
		_setReportParam: function() {
			//上个月第一天
			var firstDayOfPreMonth = new Date(new Date().getFullYear(), new Date().getMonth()-1, 1);
			var firstDayOfPreMonthStr = firstDayOfPreMonth.format("yyyy-MM-dd hh:mm:ss");
			var date = new Date();
			var day = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
			//上个月最后一天
			var lastDayOfPreMonth = new Date(new Date().getFullYear(), new Date().getMonth()-1, day);
			var lastDayOfPreMonthStr = lastDayOfPreMonth.format("yyyy-MM-dd 23:59:59");
			$("#gatherTime_start").val(firstDayOfPreMonthStr);
			$("#gatherTime_end").val(lastDayOfPreMonthStr);
			util.getDictByParentKey(null, 'id_customer', '全部','main/report/getCustomerOpt.mvc');
			//获取当前登录账户所属用户id
			operationReport._getCustomerId();
			
		},


		_getCustomerId:function() {
			$.ajax({
				"type": "post",
				"url": "main/report/getCustomerId.mvc",
				"async": false,
				"data": {},
				"dataType": "json",
				"success": function(res) {
					$("#id_customer").val(res.customerId);
				}

			});	
		},

		_getUserNameByLoginName: function(){
			$.ajax({
				"type": "post",
				"url": "main/servicePlan/getUserNamebyLoginName.mvc",
				"dataType": "json",
				"async": false,
				"success": function(resp) {
					$("#reportUser").text('报告申请人：'+resp.username);
				}
			});
		},

		_setReportCreateDate: function() {
			var now = new Date();
			var nowStr = now.format("yyyy年MM月dd日");
			$("#reportCreateDate").text("报告生成日期："+nowStr);
			$("#reportDate").text("报告时间："+ $("#gatherTime_start").val()+" 至 "+$("#gatherTime_end").val());
		},

		_setBatteryBasicInfo: function() {
			var customerId = $("#id_customer").val();
			var gatherTimeStart = $("#gatherTime_start").val();
			var gatherTimeEnd = $("#gatherTime_end").val();
			$.ajax({
				"type": "post",
				"url": "main/report/getBatteryBasicInfo.mvc",
				"async": true,
				"data": {
					"customerId":customerId,
					"gatherTimeStart":gatherTimeStart,
					"gatherTimeEnd":gatherTimeEnd
				},
				"dataType": "json",
				"beforeSend": function() {
					App.blockUI($("#operationReport"));
				},
				"success": function(res) {
					$("#customerName").text(res.customerName);
					$("#batteryNum").text(res.batteryNum);
					$("#onPowerNum").text(res.onPowerNum);
					$("#totalAlertNum").text(res.alertNum);
					$("#totalRunTime").text(res.totalRunTime+"(H)");
					$("#chargeNum").text(res.chargeNum);
				},
				"complete": function() {
					App.unblockUI($("#operationReport"));
				}

			});	
		}


	};
}();